﻿using AutoMapper;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
//using Microsoft.EntityFrameworkCore;
using NLog;
using NLog.Web;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ZxZOnlineExam.Dtos.Subject;
using ZxZOnlineExam.IService;
using ZxZOnlineExam.Models;
using ZxZOnlineExam.WebApi.Tools.Pagination;

namespace ZxZOnlineExam.WebApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    [Authorize]
    public class SubjectController : ControllerBase
    {
        private readonly ISubjectService _subjectService;
        private readonly IMapper _mapper;

        private readonly NLog.ILogger _logger;

        public SubjectController(ISubjectService subjectService,
            IMapper mapper
            )
        {
            _subjectService = subjectService;
            this._mapper = mapper;

            //_logger = logger;
            _logger = NLog.LogManager.Setup().LoadConfigurationFromAppSettings().GetCurrentClassLogger();
        }

        #region Get
        /// <summary>
        /// 此时的GetAll 自带条件查询=>类似于省市区级联查询
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        //[AllowAnonymous]
        public async Task<IActionResult> GetAllAsync(
            [FromBody] SubjectDtoForQuery subjectDtoForQuery
            )
        {
            var result = (await _subjectService.GetAsync()).AsQueryable();
            //按条件进行查找
            if (subjectDtoForQuery.Name != null && subjectDtoForQuery.Name != "")
            {
                result = result.Where(s => s.Name.Contains(subjectDtoForQuery.Name));
            }
            if (subjectDtoForQuery.Introduction != null && subjectDtoForQuery.Introduction != "")
            {
                result = result.Where(s => s.Introduction.Contains(subjectDtoForQuery.Introduction));
            }
            //限定要选择的层级，默认为1
            result = result.Where(s => s.FatherSubjectId == subjectDtoForQuery.FatherSubjectId);

            //return Ok(_mapper.Map<List<SubjectDto>>(result.ToList()));
            try
            {
                //if (result.Count() <= 0)
                //{
                //    return NotFound();
                //}
                return Ok(_mapper.Map<List<SubjectDto>>(result.ToList()));
            }
            catch (Exception ex)
            {
                _logger.Debug(ex.Message);
                return Ok(new List<SubjectDto>());
            }


        }


        /// <summary>
        /// 此时的GetAll 自带条件查询、分页功能
        /// </summary>
        /// <returns></returns>
        [HttpGet("paged")]
        [AllowAnonymous]
        public async Task<IActionResult> GetAllPagedAsync(
            [FromQuery]SubjectDtoForQuery subjectDtoForQuery,
            [FromBody]Pagination pagination
            )
        {
            var result = (await _subjectService.GetAsync()).AsQueryable();
            //按条件进行查找
            if (subjectDtoForQuery.Name!=null&&subjectDtoForQuery.Name!="")
            {
                result = result.Where(s => s.Name.Contains(subjectDtoForQuery.Name));
            }
            if (subjectDtoForQuery.Introduction!=null&&subjectDtoForQuery.Introduction!="")
            {
                result = result.Where(s => s.Introduction.Contains(subjectDtoForQuery.Introduction));
            }
            //限定要选择的层级，默认为1
            result = result.Where(s => s.FatherSubjectId == subjectDtoForQuery.FatherSubjectId);
            pagination.Total = result.Count();
            pagination.Data = _mapper.Map<List<SubjectDto>>(
                result.Skip((pagination.PageIndex - 1) * pagination.PageSize).Take(pagination.PageSize).ToList()
                );         
            return Ok(pagination);
        }

        /// <summary>
        /// Get Single By Id
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("{id}",Name = "GetSingleSubjectAsync")]
        //[AllowAnonymous]
        public async Task<IActionResult> GetSingleAsync([FromRoute]Guid id) 
        {
            var result = await _subjectService.GetSingleAsync(id);
            return Ok(_mapper.Map<SubjectDto>(result));
        }
        #endregion

        #region Create

        /// <summary>
        /// Create Subject,add to father Subject
        /// </summary>
        /// <param name="subjectDtoForCreation"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Create([FromBody]SubjectDtoForCreation subjectDtoForCreation)
        {
            var subject = _mapper.Map<Subject>(subjectDtoForCreation);
            var result = await _subjectService.CreateAsync(subject);
            if (!result)
            {
                return BadRequest("服务器错误，创建失败！");
            }
            return CreatedAtRoute(nameof(GetSingleAsync), new { id = subject.Id }, _mapper.Map<SubjectDto>(subject));
            //return Ok(_mapper.Map<SubjectDto>(subject));
        }
        #endregion

        #region Delete

        /// <summary>
        /// Delete Subject
        /// </summary>
        /// <param name="subjectDtoForCreation"></param>
        /// <returns></returns>
        [HttpDelete("{id}")]
        public async Task<IActionResult> Delete([FromRoute]Guid id)
        {
            var result = await _subjectService.FakeDeleteAsync(id);
            if (!result)
            {
                return BadRequest("服务器错误，删除失败！");
            }
            return NoContent();
        }

        /// <summary>
        /// Delete Subject
        /// </summary>
        /// <param name="subjectDtoForCreation"></param>
        /// <returns></returns>
        [HttpDelete("real/{id}")]
        [Authorize(Roles ="Admin")]
        public async Task<IActionResult> RealDelete([FromRoute] Guid id)
        {
            var result = await _subjectService.RealDeleteAsync(id);
            if (!result)
            {
                return BadRequest("服务器错误，删除失败！");
            }
            return NoContent();
        }
        #endregion

        #region Update

        /// <summary>
        /// Update Subject
        /// </summary>
        /// <param name="subjectDtoForCreation"></param>
        /// <returns></returns>
        [HttpPut]
        public async Task<IActionResult> Update([FromBody] SubjectDtoForUpdate subjectDtoForUpdate)
        {
            var subject = await _subjectService.GetSingleAsync(subjectDtoForUpdate.Id);
            subject.Introduction = subjectDtoForUpdate.Introduction;
            subject.Name = subjectDtoForUpdate.Name;
            subject.FatherSubjectId = subjectDtoForUpdate.FatherSubjectId;
            var result = await _subjectService.UpdateAsync(subject);
            if (!result)
            {
                return BadRequest("服务器错误，修改失败！");
            }
            return Ok(_mapper.Map<SubjectDto>(subject));
        }
        #endregion
    }
}
